package me.sealer.ssm.exception.handler;

import lombok.extern.slf4j.Slf4j;
import me.sealer.ssm.constant.ErrorCodeConstant;
import me.sealer.ssm.controller.dto.CommonResponse;
import me.sealer.ssm.controller.dto.ResponseHeader;
import me.sealer.ssm.core.Messageable;
import me.sealer.ssm.exception.SsmException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * ExceptionHandler
 *
 * @author sealer
 */
@Slf4j
@RestControllerAdvice
public class SsmExceptionHandler implements ApplicationContextAware {
    private ApplicationContext applicationContext;

    @ExceptionHandler(value = {Exception.class})
    Object handlerException(Exception e, HttpServletRequest request) {
        SsmException ssmException;

        if (e instanceof SsmException) {
            ssmException = (SsmException) e;
        } else if (e instanceof UnauthorizedException) {
            ssmException = new SsmException(ErrorCodeConstant.SYSTEM_NOT_AUTHORIZED);
        } else if (e instanceof UnauthenticatedException) {
            ssmException = new SsmException(ErrorCodeConstant.SYSTEM_NOT_AUTHENTICATED);
        } else if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException me = (MethodArgumentNotValidException) e;
            // 只提示第一个报错信息
            String msg = me.getBindingResult().getAllErrors().get(0).getDefaultMessage();
            ssmException = new SsmException(ErrorCodeConstant.SYSTEM_UNKNOWN_ERROR, new Object[]{msg});
        } else {
            ssmException = new SsmException(e);
        }

        String returnCode = ssmException.getReturnCode();
        Messageable messageable = ssmException.getMessageable();

        String message = applicationContext.getMessage(messageable.getMessageKey(), messageable.getArgs(), messageable.getDefaultMessage(), request.getLocale());

        if (message == null || "".equals(message)) {
            message = messageable.getDefaultMessage();
        }

        return CommonResponse.builder()
                .header(
                        ResponseHeader.builder()
                                .returnCode(returnCode)
                                .returnMessage(message)
                                .build()
                )
                .build();
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
